//
//  ActionViewController.swift
//  Uppercase Extension
//
//  Created by joker on 15/7/30.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit
import MobileCoreServices

class ActionViewController: UIViewController {
    
    
    @IBOutlet weak var textView: UITextView!
    let type = kUTTypeText as NSString as String
    
    @IBAction func cancel(sender: UIBarButtonItem) {
        let userInfo = [NSLocalizedDescriptionKey: "User cancelled"]
        let error = NSError(domain: "Extension", code: -1, userInfo: userInfo)
        extensionContext!.cancelRequestWithError(error)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        for item in extensionContext!.inputItems as! [NSExtensionItem] {
            for provider in item.attachments as! [NSItemProvider] {
                if provider.hasItemConformingToTypeIdentifier(type) {
                    provider.loadItemForTypeIdentifier(type, options: nil, completionHandler: {[weak self] (item: NSSecureCoding!, error: NSError!) in
                        let strongSelf = self!
                        if error != nil {
                            strongSelf.textView.text = "\(error)"
                        } else {
                            if let loadedItem = item as? String {
                                strongSelf.textView.text = loadedItem.uppercaseString
                            }
                        }
                        })
                }
            }
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func done() {
        // Return any edited content to the host app.
        // This template doesn't do anything, so we just echo the passed in items.
   
        let extensionItem = NSExtensionItem()
        let text = textView.text as NSString
        let itemProvider = NSItemProvider(item: text, typeIdentifier: type)
        extensionItem.attachments = [itemProvider]
        let itemsToShare = [extensionItem]
        
        extensionContext!.completeRequestReturningItems(itemsToShare, completionHandler: nil)
    }
    
}
